package com.infotel.prefecture.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class AbstractDAOJdbc {

    public AbstractDAOJdbc() {
        super();
    }
    protected void close(Connection cx, PreparedStatement ps) {
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (cx != null) {
                cx.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    protected void close(Connection cx, PreparedStatement ps, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (cx != null) {
                cx.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    protected void close(Connection cx, PreparedStatement ps, PreparedStatement ps2) {
        try {
            if (ps2 != null) {
                ps2.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (cx != null) {
                cx.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected Connection getConnection() throws Exception {
        Connection cx = getConnectionDM();
        //Connection cx = getConnectionDS();
        return cx;
    }

    private Connection getConnectionDM() throws ClassNotFoundException, SQLException {
        Connection cx = null;
         Class.forName("com.mysql.jdbc.Driver");
         String url = "jdbc:mysql://localhost:3306/cartegrise";
         cx = DriverManager.getConnection(url, "scott", "tiger");
         return cx;
    }

  
    @SuppressWarnings("unused")
    private Connection getConnectionDS() throws NamingException, SQLException {
        InitialContext ctx = new InitialContext();
        DataSource ds = (DataSource) ctx
                .lookup("java:comp/env/jdbc/CarteGriseDS");
        Connection cx = ds.getConnection();
        return cx;
    }

}